import {
  mobileLogin
} from '@/api/user'
const logout = () => {}
const getUserInfo = () => {}
import { setToken, getToken } from '@/libs/util'

export default {
  state: {
    userName: '',
    userId: '',
    mobilePhone: '',
    token: getToken()
  },
  mutations: {
    setMobilePhone (state, phone) {
      state.mobilePhone = phone
    },
    setUserName (state, name) {
      state.userName = name
    },
    setUserId (state, id) {
      state.userId = id
    },
    setToken (state, token) {
      state.token = token
      setToken(token)
    }
  },
  getters: {
    //
  },
  actions: {
    // 登录
    handleLogin ({ commit }, data) {
      // userName = userName.trim()
      return new Promise((resolve, reject) => {
        mobileLogin(data).then(res => {
          const data = res.data
          if (data.result === 'suc') {
            commit('setUserId', data.id)
            commit('setUserName', data.userName)
            commit('setMobilePhone', data.mobilePhone)
            commit('setToken', data.token)
          }
          resolve(res)
        }).catch(err => {
          reject(err)
        })
      })
    },
    // 退出登录
    handleLogOut ({ state, commit }) {
      return new Promise((resolve, reject) => {
        // logout(state.token).then(() => {
        //   commit('setUserId', '')
        //   commit('setUserName', '')
        //   commit('setMobilePhone', '')
        //   resolve()
        // }).catch(err => {
        //   reject(err)
        // })
        // 如果你的退出登录无需请求接口，则可以直接使用下面三行代码而无需使用logout调用接口
        commit('setUserId', '')
        commit('setUserName', '')
        commit('setMobilePhone', '')
        resolve()
      })
    },
    // 获取用户相关信息
    getUserInfo ({ state, commit }) {
      return new Promise((resolve, reject) => {
        try {
          getUserInfo(state.token).then(res => {
            const data = res.data
            commit('setAvatar', data.avatar)
            commit('setUserName', data.name)
            commit('setUserId', data.user_id)
            resolve(data)
          }).catch(err => {
            reject(err)
          })
        } catch (error) {
          reject(error)
        }
      })
    }
  }
}
